<?php
/**
 * VIP订单逻辑层
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\common\logic;

use app\common\model\VipOrder as VipOrderModel;

class VipOrder extends LogicBase
{
    /**
     * 获取VIP订单列表搜索条件
     */
    public function getWhere($data = [])
    {
        $where = [];
        
        // 用户ID搜索
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
        
        // 订单号搜索
        !empty($data['order_no']) && $where['order_no'] = ['like', '%' . $data['order_no'] . '%'];
        
        // 订单状态搜索
        isset($data['status']) && $data['status'] !== '' && $where['status'] = $data['status'];
        
        // 支付状态搜索
        isset($data['pay_status']) && $data['pay_status'] !== '' && $where['pay_status'] = $data['pay_status'];
        
        // 套餐类型搜索
        !empty($data['package_type']) && $where['package_type'] = $data['package_type'];
        
        // 搜索条件：套餐名称
        !empty($data['search_data']) && $where['package_name'] = ['like', '%' . $data['search_data'] . '%'];
        
        // 时间范围搜索
        !empty($data['start_time']) && $where['create_time'] = ['>=', strtotime($data['start_time'])];
        !empty($data['end_time']) && $where['create_time'] = ['<=', strtotime($data['end_time'])];
        
        // 今日订单筛选（用于后台首页"今日订单"链接）
        if (!empty($data['create_time']) && is_string($data['create_time'])) {
            $date = $data['create_time'];
            $startTime = strtotime($date . ' 00:00:00');
            $endTime = strtotime($date . ' 23:59:59');
            $where['create_time'] = ['between', [$startTime, $endTime]];
        }
        
        return $where;
    }

    /**
     * 根据订单号获取订单信息
     */
    public function getByOrderNo($data = [])
    {
        try {
            $orderNo = $data['order_no'] ?? '';
            
            if (empty($orderNo)) {
                return [RESULT_ERROR, '订单号不能为空'];
            }
            
            $order = $this->modelVipOrder->getInfo(['order_no' => $orderNo]);
            
            if (!$order) {
                return [RESULT_ERROR, '订单不存在'];
            }
            
            return [RESULT_SUCCESS, '获取成功', $order];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取用户VIP订单列表
     */
    public function getUserVipOrders($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $status = $data['status'] ?? '';
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            $where = ['user_id' => $userId];
            if (!empty($status)) {
                $where['status'] = $status;
            }
            
            $paginate = ['list_rows' => $limit, 'page' => $page];
            $list = $this->modelVipOrder->getList($where, true, 'id desc', $paginate);
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 更新订单状态
     */
    public function updateOrderStatus($data = [])
    {
        try {
            $orderId = $data['order_id'] ?? 0;
            $status = $data['status'] ?? '';
            
            if (!$orderId) {
                return [RESULT_ERROR, '订单ID不能为空'];
            }
            
            if (empty($status)) {
                return [RESULT_ERROR, '状态不能为空'];
            }
            
            $updateData = [
                'status' => $status,
                'update_time' => time()
            ];
            
            // 如果是支付成功状态，更新支付时间
            if ($status == 'paid') {
                $updateData['pay_time'] = time();
            }
            
            $result = $this->modelVipOrder->updateInfo(['id' => $orderId], $updateData);
            
            if ($result) {
                return [RESULT_SUCCESS, '状态更新成功'];
            } else {
                return [RESULT_ERROR, '状态更新失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '状态更新失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取VIP订单统计
     */
    public function getVipOrderStatistics($data = [])
    {
        try {
            $startDate = $data['start_date'] ?? '';
            $endDate = $data['end_date'] ?? '';
            
            $where = [];
            if (!empty($startDate)) {
                $where['create_time'] = ['>=', strtotime($startDate)];
            }
            if (!empty($endDate)) {
                $where['create_time'] = ['<=', strtotime($endDate . ' 23:59:59')];
            }
            
            // 总订单数
            $totalOrders = $this->modelVipOrder->stat($where, 'count');
            
            // 已支付订单数
            $paidWhere = array_merge($where, ['status' => 'paid']);
            $paidOrders = $this->modelVipOrder->stat($paidWhere, 'count');
            
            // 总收入
            $totalIncome = $this->modelVipOrder->stat($paidWhere, 'sum', 'amount');
            
            // 待支付订单数
            $pendingWhere = array_merge($where, ['status' => 'pending']);
            $pendingOrders = $this->modelVipOrder->stat($pendingWhere, 'count');
            
            $statistics = [
                'total_orders' => $totalOrders,
                'paid_orders' => $paidOrders,
                'pending_orders' => $pendingOrders,
                'total_income' => $totalIncome ?: 0,
                'conversion_rate' => $totalOrders > 0 ? round(($paidOrders / $totalOrders) * 100, 2) : 0
            ];
            
            return [RESULT_SUCCESS, '获取成功', $statistics];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取待处理VIP订单
     */
    public function getPendingVipOrders($data = [])
    {
        try {
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            
            $where = ['status' => 'pending'];
            $paginate = ['list_rows' => $limit, 'page' => $page];
            
            $list = $this->modelVipOrder->getList($where, true, 'id desc', $paginate);
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取用户最新VIP订单
     */
    public function getUserLatestVipOrder($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            $order = $this->modelVipOrder->getInfo(['user_id' => $userId], true, 'id desc');
            
            if (!$order) {
                return [RESULT_ERROR, '暂无订单记录'];
            }
            
            return [RESULT_SUCCESS, '获取成功', $order];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取邀请人佣金统计
     */
    public function getInviterCommissionStats($data = [])
    {
        try {
            $inviterId = $data['inviter_id'] ?? 0;
            $startDate = $data['start_date'] ?? '';
            $endDate = $data['end_date'] ?? '';
            
            if (!$inviterId) {
                return [RESULT_ERROR, '邀请人ID不能为空'];
            }
            
            $where = [
                'inviter_id' => $inviterId,
                'status' => 'paid'
            ];
            
            if (!empty($startDate)) {
                $where['create_time'] = ['>=', strtotime($startDate)];
            }
            if (!empty($endDate)) {
                $where['create_time'] = ['<=', strtotime($endDate . ' 23:59:59')];
            }
            
            // 佣金总额
            $totalCommission = $this->modelVipOrder->stat($where, 'sum', 'commission_amount');
            
            // 佣金订单数
            $commissionOrders = $this->modelVipOrder->stat($where, 'count');
            
            $stats = [
                'total_commission' => $totalCommission ?: 0,
                'commission_orders' => $commissionOrders,
                'average_commission' => $commissionOrders > 0 ? round($totalCommission / $commissionOrders, 2) : 0
            ];
            
            return [RESULT_SUCCESS, '获取成功', $stats];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 更新微信支付信息
     */
    public function updateWechatPayInfo($data = [])
    {
        try {
            $orderId = $data['order_id'] ?? 0;
            $wxOutTradeNo = $data['wx_out_trade_no'] ?? '';
            $wxTradeNo = $data['wx_trade_no'] ?? '';
            
            if (!$orderId) {
                return [RESULT_ERROR, '订单ID不能为空'];
            }
            
            $updateData = [
                'update_time' => time()
            ];
            
            if (!empty($wxOutTradeNo)) {
                $updateData['wx_out_trade_no'] = $wxOutTradeNo;
            }
            
            if (!empty($wxTradeNo)) {
                $updateData['wx_trade_no'] = $wxTradeNo;
            }
            
            $result = $this->modelVipOrder->updateInfo(['id' => $orderId], $updateData);
            
            if ($result) {
                return [RESULT_SUCCESS, '微信支付信息更新成功'];
            } else {
                return [RESULT_ERROR, '微信支付信息更新失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '微信支付信息更新失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 根据微信商户订单号获取订单
     */
    public function getByWxOutTradeNo($data = [])
    {
        try {
            $wxOutTradeNo = $data['wx_out_trade_no'] ?? '';
            
            if (empty($wxOutTradeNo)) {
                return [RESULT_ERROR, '微信商户订单号不能为空'];
            }
            
            $order = $this->modelVipOrder->getInfo(['wx_out_trade_no' => $wxOutTradeNo]);
            
            if (!$order) {
                return [RESULT_ERROR, '订单不存在'];
            }
            
            return [RESULT_SUCCESS, '获取成功', $order];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 根据微信交易号获取订单
     */
    public function getByWxTradeNo($data = [])
    {
        try {
            $wxTradeNo = $data['wx_trade_no'] ?? '';
            
            if (empty($wxTradeNo)) {
                return [RESULT_ERROR, '微信交易号不能为空'];
            }
            
            $order = $this->modelVipOrder->getInfo(['wx_trade_no' => $wxTradeNo]);
            
            if (!$order) {
                return [RESULT_ERROR, '订单不存在'];
            }
            
            return [RESULT_SUCCESS, '获取成功', $order];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
}